// piece: Array<Object> 数据结构
// piece[n].id: Number, // 裁片id
// piece[n].surfaceName: String, // 裁片名称
// piece[n].maskImage: Sring, // 遮罩图片，宽度高度与容器一至
// piece[n].outerWidth: Number, // 容器宽度
// piece[n].outerHeight: Number, // 容器高度
// piece[n].realWidth: Number, // 裁片真实宽度
// piece[n].realHeight: Number, // 裁片真实高度
// piece[n].realScale: Number, // 裁片真实宽高和canvas宽高比例
// piece[n].canvasLeft: Number, // 裁片相对容器的左边的位置
// piece[n].canvasTop: Number,  // 裁片相对容器的左边的位置
// piece[n].canvasWidth: Number, // 裁片的宽度
// piece[n].canvasHeight: Number, // 裁片的宽度
// piece[n].layers: Array<Object>, // 图层

// piece[m].layers[n].type: String, // 类型[image|text]
// piece[m].layers[n].rotate: Number, // 旋转角度
// piece[m].layers[n].url: String,
// piece[m].layers[n].x: Number, // 图片最终显示x轴坐标
// piece[m].layers[n].y: Number, // 图片最终显示Y轴坐标
// piece[m].layers[n].w: Number, // 图片最终显示宽度
// piece[m].layers[n].h: Number, // 图片最终显示调试
// piece[m].layers[n].flipHor: Boolean, // 横向翻转
// piece[m].layers[n].flipVer: Boolean, // 竖向翻转

// 图片
// piece[m].layers[n].imageName: String,
// piece[m].layers[n].imageW: Number, // 图片宽度
// piece[m].layers[n].imageH: Number, // 图片高度
// piece[m].layers[n].cutX: Number, // 图片裁剪左偏移
// piece[m].layers[n].cutY: Number, // 图片裁剪右偏移
// piece[m].layers[n].cutW: Number, // 图片裁剪宽度
// piece[m].layers[n].cutH: Number, // 图片裁剪高度
// piece[m].layers[n].tiledType: String, // 平铺方式[basic|mirror|brick|drop]
// piece[m].layers[n].tiledHor: Number, // 平铺横向间距
// piece[m].layers[n].tiledver: Number, // 平铺横向间距

// 文字
// piece[m].layers[n].text: String, // 文字内容
// piece[m].layers[n].fontFamily: String, // 字体
// piece[m].layers[n].fontColor: String, // 颜色
// piece[m].layers[n].fontSize: Number, // 字号大小
// piece[m].layers[n].fontArc: Number, // 文字弧度
// piece[m].layers[n].letterSpacing: Number, // 字间距
// piece[m].layers[n].outlineColor: String, // 外描边颜色
// piece[m].layers[n].outlineWeight: Number, // 外描边大小，字号大小百分比
// piece[m].layers[n].outlineOffset: Number, // 外描边与文字距离，字号大小百分比
// piece[m].layers[n].shadowColor: String, // 阴影颜色
// piece[m].layers[n].shadowDistance: Number, // 阴影宽度，字号大小百分比
// piece[m].layers[n].shadowAngle: Number, // 阴影角度
// piece[m].layers[n].tiledType: String, // 平铺方式[basic|mirror|brick|drop]
// piece[m].layers[n].tiledHor: Number, // 平铺横向间距
// piece[m].layers[n].tiledver: Number, // 平铺横向间距

// model: Array<Object> 数据结构
// model[m].id: Number // 裁片id
// model[m].name: String // 模特名称
// model[m].maskImage: String // 遮罩图片，宽度高度与容器一至
// model[m].outerHeight: Number // 容器宽度
// model[m].outerWidth: Number // 容器高度
// model[m].productId: Number // 模特所在产品id
// model[m].mapping: Array<Object> // 数据结构
// model[m].mapping[n].surfaceName: String, // 对应的裁片
// model[m].mapping[n].variantDeform: Number, // 变形系数
// model[m].mapping[n].variantFactor: Number, // 变形偏移量
// model[m].mapping[n].height: Number, // 显示裁片的高度
// model[m].mapping[n].width: Number, // 显示裁片的宽度
// model[m].mapping[n].rotate: Number, // 显示裁片的角度
// model[m].mapping[n].x: Number, // 显示区域x偏移
// model[m].mapping[n].y: Number, // 显示y偏移

import DesignResource from "@/utils/DesignResource.js";
import DesignUtils from "@/utils/DesignUtils.js";

const state = () => ({
    activeColor: 0, // 默认颜色
    activeModel: 0, // 当前选中的模特
    activeModelTag: "hanging", // 当前选中的模特
    activePiece: 0, // 当前选中的绘制版
    activeLayer: -1, // 当前选中编辑图层
    lastActiveLayer: -1, // 最后一次选中的图层
    activeDst: -1, // 当前选中编辑版带
    colors: [], // 颜色列表
    platens: [], // 刺绣压框
    pieces: [], // 裁片列表
    models: [], // 模特列表

    oversize_dst: [], // 版带超出绣框范围
    overlap_dst: [], // 重叠的版带
    exceed_stitches: [], // 版带针数超出
    exceed_colors: [], // 针数换线超出

    // 用户品牌领标
    necklabelInfo: {
        active: 0, // 选中的品牌领标
        type: "", // light|dark
        loading: false,
        inited: false,
        cache: null, // 缓存旧的
        list: [],
    },
});

const getters = {
    getNecklabelInfo(state) {
        return state.necklabelInfo;
    },
    // 颜色列表
    getColors(state) {
        return state.colors || [];
    },
    // 模特
    getModels(state) {
        return state.models || [];
        // return (state.models || []).filter(
        //     (m) => m.model_tag == state.activeModelTag
        // );
    },
    // 刺绣框
    getPlatens(state) {
        return state.platens || [];
    },
    // 线框图
    getSurfaces(state) {
        const pieces = state.pieces || [];
        const surfaces = [];

        pieces.map((item) => {
            let select = surfaces.find(
                (s) => s.surface_name == item.surface_name
            );
            if (!select) {
                // 线框图
                surfaces.push({
                    surface_name: item.surface_name,
                    mask_image: item.mask_image,
                    outer_width: item.outer_width,
                    outer_height: item.outer_height,
                    pieces: [item],
                });
            } else {
                select.pieces.push(item);
            }
        });

        return surfaces;
    },

    // 裁片
    getPieces(state) {
        const pieces = state.pieces || [];
        return pieces;
    },

    // 获取自定义设计
    getPiecesCustomize(state) {
        const pieces = state.pieces || [];
        const custom = [];

        pieces.forEach((piece) => {
            (piece.layers || []).forEach((layer) => {
                layer.customize && custom.push(layer);
            });
        });
        return custom;
    },

    // 衣服颜色
    getActiveColor(state) {
        if (state.colors && state.colors.length > 0) {
            return state.colors[state.activeColor];
        } else {
            return null;
        }
    },
    // 当前展示的模特
    getActiveModel(state) {
        if (state.models && state.models.length > 0) {
            return state.models[state.activeModel];
        } else {
            return null;
        }
    },
    getActiveModelTag(state) {
        return state.activeModelTag || "hanging";
    },

    // 当前操作的线框图
    getActiveSurface(state) {
        let surfaces = getters.getSurfaces(state);
        let activePiece = getters.getActivePiece(state);
        if (surfaces.length > 0 && activePiece) {
            return surfaces.find((surface) =>
                surface.pieces.find((p) => p.id == activePiece.id)
            );
        } else {
            return null;
        }
    },

    // 当前操作的裁片
    getActivePiece(state) {
        const pieces = getters.getPieces(state);
        if (pieces.length == 0) {
            return null;
        } else {
            return pieces[state.activePiece];
        }
    },

    // 设计面价格
    getPiecesPrice(state) {
        // 优惠的价格，正面或背面优惠一个最高的价格
        let free = null;
        // 设计的面
        const design = [];
        const pieces = getters.getPieces(state);

        pieces.map((piece) => {
            if (piece.layers && piece.layers.length > 0) {
                let name = piece.canvas_name;

                let item = {
                    name: name,
                    value: 0,
                    id: piece.id,
                    piece: piece,
                };

                if (piece.type == 2) {
                    item.value = piece.layers.reduce(
                        (pre, cur) => pre + cur.price,
                        0
                    );
                } else {
                    item.value = piece.price || 0;
                }

                if (piece.type == 1 && /^Back Side|Front Side/.test(name)) {
                    if (!free) {
                        free = item;
                    } else if (item.value > free.value) {
                        free = item;
                    }
                }

                design.push(item);
            }
        });

        free && (free.value = 0);

        return design;
    },

    // 当前操作的裁片的图层
    getActivePieceLayers(state) {
        let activePiece = getters.getActivePiece(state);
        if (activePiece) {
            return activePiece.layers || [];
        } else {
            return [];
        }
    },

    // 当前选中图层
    getActiveLayer(state) {
        return getters.getActivePieceLayers(state)[state.activeLayer];
    },

    // 最后选中图层
    getLastActiveLayer(state) {
        return getters.getActivePieceLayers(state)[state.lastActiveLayer];
    },

    // 当前选中图层
    getActiveDst(state) {
        let activeLayer = getters.getActiveLayer(state);
        let list = (activeLayer || {}).dists || [];
        return list[state.activeDst];
    },

    // 判断是否可以下单
    getSaveAble(state) {
        let piece = getters.getPieces(state);
        let able = piece.filter((item) => {
            return item.layers && item.layers.length > 0;
        });

        return able.length > 0;
    },

    // 获取当前领标的设计面信息
    getNecklabelPiece(state) {
        let pieces = getters.getPieces(state);
        let necklabel = pieces.filter(
            (item) => item.canvas_name == "Neck Label Inner"
        );
        return necklabel[0];
    },
};

const mutations = {
    // 设置id
    // SET_ID(state, payload){
    //   state.product_id = (payload || {}).product_id;
    //   state.template_id = (payload || {}).template_id;
    // },

    SET_NECKLABEL_INFO(state, object) {
        const option = object || { active: 0, cache: null, type: "" };
        const pieces = getters.getPieces(state);
        const cache = pieces.find((i) => i.canvas_name == "Neck Label Inner");

        state.necklabelInfo.active = option.active;
        state.necklabelInfo.type = option.type;
        state.necklabelInfo.loading = false;
        state.necklabelInfo.inited = false;
        state.necklabelInfo.list = option.list || [];
        state.necklabelInfo.cache = cache
            ? JSON.parse(JSON.stringify(cache))
            : null;
    },

    // 设置领标
    SET_NECKLABEL_ACTIVE(state, object) {
        const piece = getters.getNecklabelPiece(state);
        const activeColor = getters.getActiveColor(state);
        const necklabelInfo = state.necklabelInfo;

        if (!piece) {
            // 没有准备好
        } else if (object && activeColor) {
            const active = object.id;
            const type = activeColor.is_white ? "dark" : "light";
            const necklabel = activeColor.is_white ? object.dark : object.light;

            if (necklabelInfo.active != active || necklabelInfo.type != type) {
                necklabelInfo.active = active;
                necklabelInfo.type = type;
                Object.keys(necklabel).map((key) => {
                    piece[key] = necklabel[key];
                });
            }
        } else {
            // 还原为原来的领标状态
            necklabelInfo.active = 0;
            necklabelInfo.type = "";
            Object.keys(state.necklabelInfo.cache).map((key) => {
                piece[key] = state.necklabelInfo.cache[key];
            });
        }
    },

    // 重置颜色列表
    SET_COLORS(state, array) {
        state.colors = array;
    },
    // 重置模特列表
    SET_MODELS(state, array) {
        state.models = array;
    },
    // 设置刺绣框
    SET_PLATENS(state, array) {
        state.platens = array;
    },
    // 重置裁片列表
    SET_PIECES(state, array) {
        state.pieces = array;
    },
    // 选中颜色
    SET_ACTIVE_COLOR(state, object) {
        state.activeColor = state.colors.indexOf(object);

        // 如果有设置品牌领标，则设置领标深浅色
        // 只判断颜色不同时才切换
        if (state.necklabelInfo.active) {
            const list = state.necklabelInfo.list || [];
            const active = state.necklabelInfo.active || [];
            const necklabel = list.filter((i) => i.id == active)[0];

            mutations.SET_NECKLABEL_ACTIVE(state, necklabel);

            // const necklabelRaw = necklabelInfo.list.filter(
            //     (i) => i.id == necklabelInfo.active
            // );
            // const necklabel = getters.getNecklabelPiece(state);
            // const piece = (necklabelRaw[0] || {})[type];
            // if (piece) {
            //     necklabelInfo.type = type;
            //     Object.keys(piece).map((key) => (necklabel[key] = piece[key]));
            // }
            // // 判断当前的显示类型
            // const is_light = /light.svg/.test(state.necklabel.mask_image);
            // const activeNecklabel = state.necklabelInfo.list.filter(
            //     (i) => i.id == state.necklabelInfo.active
            // )[0];
            // const activeColor = getters.getActiveColor(state);
            // if (!activeNecklabel || !activeColor) {
            //     // 没有选中的领标
            // } else if (is_light && !activeColor.is_white) {
            //     // 深色
            //     state.necklabel = activeNecklabel.dark;
            // } else if (!is_light && activeColor.is_white) {
            //     // 浅色
            //     state.necklabel = activeNecklabel.light;
            // }
        }
    },
    // 选中模特
    SET_ACTIVE_MODEL(state, object) {
        state.activeModel = state.models.indexOf(object);
    },

    // 切换模特类型
    SET_ACTIVE_MODEL_TAG(state, tag) {
        if (tag != state.activeModelTag) {
            state.activeModelTag = tag;
            state.activeModel = state.models.findIndex(
                (m) => m.model_tag == tag
            );
        }
    },

    // 选中裁片
    SET_ACTIVE_PIECE(state, object) {
        // const name = (object || {}).canvas_name;
        // const names = getters.getPieces(state).map((i) => i.canvas_name);
        // state.activePiece = names.indexOf(name);

        state.activePiece = getters.getPieces(state).indexOf(object);
    },

    // 添加图层
    ADD_LAYER(state, object) {
        let piece = getters.getActivePiece(state);
        let isArray =
            Object.prototype.toString.call(piece.layers) == "[object Array]";

        if (!piece) {
            // 没有选中图片
        } else if (isArray) {
            piece.layers.push(object);
        } else {
            piece.layers = [object];
        }
    },

    // 插入图层到指定位置
    PUT_LAYER(state, object) {
        let piece = getters.getActivePiece(state);
        let layer = object.layer;
        let index = object.index;

        if (!piece) {
            // 没有选中图片
        } else if (layer) {
            piece.layers.splice(index, 0, layer);
        }
    },

    // 删除图层
    DEL_LAYER(state, object) {
        let piece = getters.getActivePiece(state);

        if (!piece) {
            let pieces = getters.getPieces(state);
            pieces.map((piece) => {
                const index = piece.layers.indexOf(object);
                index >= 0 && layers.splice(index, 1);
            });
        } else {
            let layers = piece.layers || [];
            let index = layers.indexOf(object);
            index >= 0 && layers.splice(index, 1);
        }
    },
    // 重置图层
    SET_LAYERS(state, array) {
        let piece = getters.getActivePiece(state);
        piece && piece.layers.splice(0, piece.layers.length, ...array);
    },

    // 选中图层
    SET_ACTIVE_LAYER(state, object) {
        let layers = getters.getActivePieceLayers(state);
        let index = layers.indexOf(object);
        if (state.activeLayer == index) {
            state.activeLayer = -1;
        } else {
            state.activeLayer = index;
            state.lastActiveLayer = index < 0 ? state.lastActiveLayer : index;
        }
    },

    // 选中图层
    SET_ACTIVE_LAYER_INDEX(state, index) {
        state.activeLayer = index;
        state.lastActiveLayer = index < 0 ? state.lastActiveLayer : index;
    },

    // 修改选中图层的具体的内容
    SET_LAYER_VALUE(state, object) {
        let layer = getters.getActiveLayer(state);
        layer &&
            Object.keys(object).map((key) => {
                let now = object[key];
                let old = layer[key];
                if (old === undefined) {
                    // 未赋值
                } else if (old === now) {
                    // 相等的不用管
                } else {
                    layer[key] = now;
                }
            });
    },

    SET_ACTIVE_LAYER_PRICE(state, object) {
        if (object && object.dists) {
            const platen = state.platens.find(
                (i) => i.code == object.platens_id
            );
            object.stitches_count = object.dists.reduce(
                (p, c) => p + c.stitches_count || 0,
                0
            );
            object.price = DesignUtils.getEmbPrice(
                object.stitches_count,
                platen
            );
        }
    },

    SET_DST_VALUE(state, object) {
        const format = Object.assign({}, object);
        const layer = getters.getActiveLayer(state);
        const dst = getters.getActiveDst(state);

        if (dst) {
            Object.keys(format).map((key) => {
                let now = format[key];
                let old = dst[key];
                if (old === undefined) {
                    // 未赋值
                } else if (old === now) {
                    // 相等的不用管
                } else {
                    dst[key] = now;
                }
            });
        }
    },

    SET_ACTIVE_DST_INDEX(state, index) {
        state.activeDst = index;
    },

    SET_OVERSIZE_DST(state, option) {
        state.oversize_dst = option;
    },
    SET_OVERLAP_DST(state, option) {
        state.overlap_dst = option;
    },

    SET_EXCEED_STITCHES(state, option) {
        state.exceed_stitches = option;
    },
    SET_EXCEED_COLORS(state, option) {
        state.exceed_colors = option;
    },
};

const actions = {
    // 删除图层
    delLayer(store, payload) {
        let activeLayer = store.getters.getActiveLayer;
        let isActive = activeLayer && activeLayer == payload;
        store.commit("DEL_LAYER", payload);
        if (isActive) {
            store.commit("SET_ACTIVE_LAYER", null);
        }
    },

    // 获取领标
    getNecklabelList(store, payload) {
        const necklabelInfo = store.state.necklabelInfo;
        if (necklabelInfo.loading || necklabelInfo.inited) {
            // 请求中
        } else {
            const pieceFormat = (pieceStr) => {
                let result = pieceStr;

                if (typeof pieceStr === "string") {
                    try {
                        result = JSON.parse(pieceStr);
                    } catch (err) {
                        console.log(err);
                    }
                }

                if (typeof result.layers === "string") {
                    try {
                        result.layers = JSON.parse(result.layers);
                    } catch (err) {
                        console.log(err);
                    }
                }

                result.type = 1;
                return result;
            };

            const loadNecklabel = (necklabelList) => {
                const promises = [];
                const option = {
                    type: "simple",
                    form: "materials",
                };

                necklabelList.map((design) => {
                    [design.light, design.dark].map((piece) => {
                        // 加载背景图
                        if (piece.mask_image) {
                            DesignResource.loadImage(piece.mask_image, option);
                        }

                        // 加载图层的图片
                        piece.layers.map((layer) => {
                            if (layer.type == "image" && layer.url) {
                                promises.push(
                                    DesignResource.loadImage(layer.url, option)
                                );
                            }
                        });
                    });
                });

                // 加载图片完成后，切换
                Promise.all(promises).then((res) =>
                    store.commit(
                        "SET_ACTIVE_COLOR",
                        getters.getActiveColor(store.state)
                    )
                );
            };

            necklabelInfo.loading = true;
            this.$http("BrandLabel.search", {}).then((response) => {
                if (response.code === 0) {
                    const list = [];
                    (response.data || []).map((item) => {
                        if (item.dark_design && item.light_design) {
                            const cache = necklabelInfo.cache || {};
                            const design = {
                                id: item.id,
                                title: item.title,
                                dark: pieceFormat(item.dark_design),
                                light: pieceFormat(item.light_design),
                            };

                            design.dark.id = design.id;
                            design.light.id = design.id;
                            design.dark.price = cache.price || 0;
                            design.light.price = cache.price || 0;
                            list.push(design);
                        }
                    });
                    necklabelInfo.loading = false;
                    necklabelInfo.inited = true;
                    necklabelInfo.list = list;

                    loadNecklabel(necklabelInfo.list);
                } else {
                    // 请求错误
                    necklabelInfo.loading = false;
                    necklabelInfo.inited = false;
                }
            });
        }
    },
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
};
